//
// Copyright 2011 ReedRex Corp
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// BookListViewController.m
// Cloud BookShelf
//
// Created by Shunichi Takagi on 11/02/25.
//

#import "BookListViewController.h"

@implementation BookListViewController

@synthesize bookService;
@synthesize books;

#pragma mark -
#pragma mark Initialization

- (id)initWithStyle:(UITableViewStyle)style {
    // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    self = [super initWithStyle:style];
    if (self) {
		UISearchBar* bar = [[UISearchBar alloc] initWithFrame:CGRectMake(0,0,280,44)];
		bar.delegate = self;
		bar.placeholder = @"タイトルで検索";
		self.navigationItem.titleView = bar;
		
		StorageClient *client = [[StorageClient alloc] initWithAccountName:@"<<INSERT YOUR AZURE STORAGE ACCOUNT NAME>>"
																	andKey:@"<<INSERT YOUR AZURE STORAGE ACCOUNT KEY>>"];
		
		self.bookService = [[BookService alloc] initWithClient:client enabledBatch:NO];
	}
	
    return self;
}

- (void) reload:(Queries *)aQueries {
	@try {
		self.books = [bookService findByQueries:aQueries];
		
		[self.tableView reloadData];
	}
	@catch (NSException *e) {
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:[e name] message:[e reason] delegate:nil cancelButtonTitle:@"確認" otherButtonTitles:nil];
		[alert show];
	}
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
	NSString *text = [searchBar text];
	
	[self reload:[Queries with:@"title" eq:text]];
	[searchBar resignFirstResponder];
}

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
	[self reload:[Queries withEmpty]];
}


#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [books count] + 2;
}


// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }
    
	if( [indexPath row] == 0 ) {
		cell.textLabel.text = @"新しい本を追加する";
		cell.detailTextLabel.text = @"";
	} else if ( [indexPath row]-1 < [books count] ) {
		Book *book = [books objectAtIndex:[indexPath row]-1];
		cell.imageView.image = [bookService fetchImage:book];
		cell.textLabel.text = book.title;
		cell.detailTextLabel.text = [NSString stringWithFormat:@"著者: %@ レート: %@", book.author, book.rate];
    } else {
		cell.textLabel.text = @"全て表示する";
		cell.detailTextLabel.text = @"";
	}
	
	return cell;
}


// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return ( [indexPath row] >= 1 && [indexPath row] < [books count] + 1 );
}


// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
	UIActivityIndicatorView *ai = [[UIActivityIndicatorView alloc] init];
	ai.frame = CGRectMake(0, 0, 25, 25);
	ai.center = self.view.center;
	ai.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
	[self.view addSubview:ai];
	
	[ai startAnimating];
	
	if (editingStyle == UITableViewCellEditingStyleDelete) {
		Book *book = [books objectAtIndex:[indexPath row]-1];
		
		@try {
			[bookService remove:book];
		}
		@catch (NSException *e) {
			UIAlertView *alert = [[UIAlertView alloc] init];
			alert.title = [e name];
			alert.message = [e reason];
			[alert addButtonWithTitle:@"確認"];
			[alert show];
		}
		
		[self reload:[Queries withEmpty]];
    }
	
	[ai stopAnimating];
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
	
	int row = [indexPath row];
	
	if ( row < [books count] + 1 ){
		Book *book = ( row > 0 && row < [books count]+1 ? [books objectAtIndex:row-1] : nil );
		BookDetailViewController *detailView = [[BookDetailViewController alloc] initWithBook:book andService:bookService];
		
		[self.navigationController pushViewController:detailView animated:YES];
	} else {
		[self reload:[Queries withEmpty]];
		//[self reload:@""];
	}
}


#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewDidUnload {
}


- (void)dealloc {
	[bookService release];
	bookService = nil;
	
	[books release];
	books = nil;
	
    [super dealloc];
}


@end

